const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '120.78.121.135',
  port: 3306,
  user: 'root',
  password: 'Hbbd8991@',
  database: 'ticket_dev',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

let pool;

// 创建连接池
function createPool() {
  if (!pool) {
    pool = mysql.createPool(dbConfig);
  }
  return pool;
}

// 获取数据库连接
async function getConnection() {
  const poolConnection = createPool();
  return await poolConnection.getConnection();
}

// 执行查询
async function query(sql, params = []) {
  const connection = await getConnection();
  try {
    const [results] = await connection.execute(sql, params);
    return results;
  } finally {
    connection.release();
  }
}

// 执行事务
async function transaction(callback) {
  const connection = await getConnection();
  try {
    await connection.beginTransaction();
    const result = await callback(connection);
    await connection.commit();
    return result;
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
}

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await getConnection();
    console.log('数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error.message);
    return false;
  }
}

module.exports = {
  query,
  transaction,
  testConnection,
  getConnection,
  pool: () => pool
};